#!/usr/bin/env python

# -*- coding: utf-8 -*-

#    Copyright (C) 2014 by Promotux
#                       di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of OdCollect.

#    OdCollect is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    OdCollect is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with OdCollect.  If not, see <http://www.gnu.org/licenses/>.


import urllib2
import urllib
import json
import pprint

# Put the details of the dataset we're going to create into a dict.
dataset_dict = {
    #'name': 'francesco_api_import A',
    #'notes': 'importato da api remota',
     #'owner_org':"comune",
     #"author":"Francesco Meloni",
    #"title": "questo dovrebbe essere il titolo di un dataset2",
    #"url":"http://www.opendatagpf.it"
}

## Use the json module to dump the dictionary to a string for posting.
data_string = urllib.quote(json.dumps(dataset_dict))

## We'll use the package_create function to create a new dataset.
#request = urllib2.Request(
#    'http://test.opendatagpf.it/api/action/package_create')

## Creating a dataset requires an authorization header.
## Replace *** with your API key, from your user account on the CKAN site
## that you're creating the dataset on.
#request.add_header('Authorization', 'ccd15299-e006-482a-8034-d99f655699d0')

## Make the HTTP request.
#response = urllib2.urlopen(request, data_string)
#assert response.code == 200

## Use the json module to load CKAN's response into a dictionary.
#response_dict = json.loads(response.read())
#assert response_dict['success'] is True

## package_create returns the created package as its result.
#created_package = response_dict['result']
#print "AHHHHHHHHHHHHHHHHHHHHHHHH 7f17d65f-ec16-4a7e-8146-4eef3d0d100a"
#pprint.pprint(created_package)

import ckanapi

mysite = ckanapi.RemoteCKAN('http://test.opendatagpf.it',
    apikey='ccd15299-e006-482a-8034-d99f655699d0',
    user_agent='ckanapiexample/1.0 (+http://example.com/my/website)')
print "MYSITE", mysite
try:
    pkg = mysite.action.package_create( owner_org="comune",
                                        name='francesco_api_import_b',
                                        notes='importato da api remota',
                                        author = "Francesco Meloni",
                                        title = "questo dovrebbe essere il titolo di un dataset2",
                                        url = "http://www.opendatagpf.it")

    print " PKGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG", pkg
    mysite.action.resource_create(
    package_id=pkg["id"],
    name="Proviamo da dare un nome al file da script",
    upload=open('/home/vete/consumabili.csv'))
except:
    request = urllib2.Request(
        "http://test.opendatagpf.it/api/3/action/package_show?id=francesco_api_import_b")
    response = urllib2.urlopen(request)
    response_dict = json.loads(response.read())
    print "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP", response_dict["success"],response_dict["result"]["id"]
    mysite.action.resource_create(
    package_id=response_dict["result"]["id"],
    name="Proviamo da dare un nome al file da script ma da esistente",
    upload=open('/home/vete/consumabili.csv'))
#mysite.action.group_list(id='comune')
#mysite.action.resource_create(
    #package_id='7f17d65f-ec16-4a7e-8146-4eef3d0d100a',
    #name="Proviamo da dare un nome al file da script",
    #upload=open('/home/vete/consumabili.csv'))
    """{u'owner_org': u'e842f6b4-4129-4c90-b4cb-e64c9de522d1', u'maintainer': None, u'relationships_as_object': [], u'private': False, u'maintainer_email': None, u'revision_timestamp': u'2014-05-29T17:04:58.575059', u'id': u'd1704718-3ad8-4128-b58d-5f42764cb273', u'metadata_created': u'2014-05-29T17:04:58.575059', u'metadata_modified': u'2014-05-29T17:04:58.587031', u'author': u'Francesco Meloni', u'author_email': None, u'state': u'active', u'version': None, u'license_id': None, u'type': u'dataset', u'resources': [], u'num_resources': 0, u'tags': [], u'title': u'questo dovrebbe essere il titolo di un dataset2', u'tracking_summary': {u'total': 0, u'recent': 0}, u'groups': [], u'creator_user_id': u'66aa3be6-1948-4142-8a80-636574c19e9d', u'relationships_as_subject': [], u'num_tags': 0, u'name': u'francesco_api_import_', u'isopen': False, u'url': u'http://www.opendatagpf.it', u'notes': u'importato da api remota', u'license_title': None, u'extras': [], u'organization': {u'description': u'Datasets inseriti da personale autorizzato per conto del Comune di .....', u'title': u'Comune', u'created': u'2014-03-12T13:45:08.485013', u'approval_status': u'approved', u'revision_timestamp': u'2014-03-12T12:48:05.636491', u'is_organization': True, u'state': u'active', u'image_url': u'', u'revision_id': u'00f48480-336b-4d4c-a42f-88b660946a90', u'type': u'organization', u'id': u'e842f6b4-4129-4c90-b4cb-e64c9de522d1', u'name': u'comune'}, u'revision_id': u'b3472ba4-359b-4d30-8a81-7f27e64cb091'}
    """
